using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Skinner
{
    public partial class StyleEdit : Form
    {
        private StyleEdit()
        {
            InitializeComponent();
        }

        private StyleRule _styleRule = null;
        private string _originalText;
        private mshtml.IHTMLStyleSheetRule _rule;

        internal StyleEdit(StyleRule styleRule)
        {
            InitializeComponent();
            _styleRule = styleRule;
            _rule = _styleRule.Rule;
            txtCSS.Text = _rule.style.cssText;
            lblStyle.Text = _rule.selectorText;
            _originalText = _rule.selectorText;

            //Rule appears more than once, open multiple editors.
            if (_styleRule.Rules.Count > 1)
            {
                for (int i = 1; i < _styleRule.Rules.Count; i++)
                {
                    StyleEdit editor = new StyleEdit(_styleRule, _styleRule.Rules[i]);
                    editor.Show();
                }
            }
        }

        private StyleEdit(StyleRule styleRule, mshtml.IHTMLStyleSheetRule rule)
        {
            InitializeComponent();
            _styleRule = styleRule;
            _rule = rule;
            txtCSS.Text = _rule.style.cssText;
            lblStyle.Text = _rule.selectorText;
            _originalText = _rule.selectorText;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                _rule.style.cssText = txtCSS.Text;
                this.Close();
                return;
            }
            catch (SystemException ex)
            {
                MessageBox.Show(string.Format("An error occured. Check your syntax! Error {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            _rule.style.cssText = _originalText;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnImage_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string background = string.Format("URL({0})", openFileDialog.FileName);
                _rule.style.backgroundImage = background;
                txtCSS.Text = _rule.style.cssText;
                _styleRule.StyleSheet.ReplacementImages.Add(_rule.selectorText, openFileDialog.FileName);
            }
        }
    }
}